/*
 * Package il.ac.biu.cs.grossmm.impl.activeData
 * File SqlPublicationPoint.java
 * 
 * This is a part of presence service framework prototype. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.

 * You should have received a copy of the GNU Lesser General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.impl.activeData;

import il.ac.biu.cs.grossmm.api.OperationFailedException;
import il.ac.biu.cs.grossmm.api.data.Node;
import il.ac.biu.cs.grossmm.api.data.NodeType;
import il.ac.biu.cs.grossmm.api.data.Root;
import il.ac.biu.cs.grossmm.api.flow.NodeExistsException;
import il.ac.biu.cs.grossmm.api.flow.NodeManipulator;
import il.ac.biu.cs.grossmm.api.flow.PublicationPointBase;
import il.ac.biu.cs.grossmm.api.flow.Subscriber;
import il.ac.biu.cs.grossmm.api.flow.Status;
import il.ac.biu.cs.grossmm.api.flow.Track;
import il.ac.biu.cs.grossmm.api.keys.Key;
import il.ac.biu.cs.grossmm.api.keys.KeyPattern;
import il.ac.biu.cs.grossmm.impl.activeData.SqlSynch.DeletedException;

import java.sql.SQLException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.apache.log4j.Logger;

public class SqlPublicationPoint<N> extends PublicationPointBase<N> {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger
			.getLogger(SqlPublicationPoint.class);

	final SqlRootMapping<N> rootMapping;
	
	final DataLayer<N> dataLayer;

	Map<Key, SubscriptionImpl<N>> subscriptions;
	
	

	public SqlPublicationPoint(SqlRootMapping<N> sqlRootMapping,
			DataLayer<N> dataLayer, KeyPattern pattern, String name,
			Cache<SqlNodeBase, Object[]> valuesCache,
			Cache<SqlNodeSet, Set<SqlInnerNode>> subnodesCache,
			int rootCacheSize) throws SQLException

	{
		super(dataLayer.nodeType, pattern, name);
		this.dataLayer = dataLayer;
		this.rootMapping = sqlRootMapping;
		this.subscriptions = new HashMap<Key, SubscriptionImpl<N>>();

		sqlRootMapping.prepare(valuesCache, subnodesCache, 100);
	}

	public synchronized Root<N> createNode(Key key, boolean mayExist)
			throws OperationFailedException, NodeExistsException {
		try {
			SqlRootNode<N> root = rootMapping.create(key, mayExist);

			SubscriptionImpl<N> subscription = subscriptions.get(key);

			if (subscription != null)
				subscription.activate(root);

			return root;
		} catch (SQLException e) {
			throw new OperationFailedException(e);
		}
	}

	public synchronized SqlRootNode<N> getRoot(Key key)
			throws OperationFailedException {
		return rootMapping.get(key);
	}

	public NodeManipulator writeLock(Node node) throws OperationFailedException {
		SqlRootNode<N> sqlRoot = (SqlRootNode<N>) node.getRoot();

		try {
			return doWriteLock(sqlRoot);
		} catch (Exception e) {
			throw new OperationFailedException(e);
		}
	}

	public void writeUnlock(Node node) {
		SqlRootNode<N> sqlRoot = (SqlRootNode<N>) node.getRoot();

		doWriteUnlock(sqlRoot);
	}

	private NodeManipulator doWriteLock(SqlRootNode<N> sqlRoot)
			throws Exception {
		SqlSynch sync = sqlRoot.getSynch();

		SqlManipulator man = new SqlManipulator(this, sqlRoot);

		sync.writeLock(man);

		return man;
	}

	private void doWriteUnlock(SqlRootNode<N> sqlRoot) {
		try {
			SqlManipulator man = sqlRoot.getSynch().writeToNotifyRelock();

			// apply all changes automically
			try {
				man.applyChanges();
			} catch (Exception e) {
				e.printStackTrace();
				logger.error(e);
			}

			SubscriptionImpl<N> sub = sqlRoot.getSubscription();

			if (sub != null) {
				sub.nodeUpdated(new SqlEventInspector(man));
			}

		} catch (DeletedException e) {
			// nothing?
		}

		sqlRoot.getSynch().notifyUnlock();
	}

	@SuppressWarnings("unchecked")
	public NodeType<N> getNodeType() {
		return rootMapping.nodeType;
	}

	public KeyPattern getPattern() {
		return pattern;
	}

	public SubscriptionImpl<N> subscribe(Subscriber<N> subscriber, Key key,
			Track track) {
		SqlRootNode<N> root;
		SubscriptionImpl<N> subscription;

		assert !subscriptions.containsKey(key);

		try {
			root = getRoot(key);
		} catch (OperationFailedException e) {
			e.printStackTrace();
			root = null;
		}

		if (root == null) {
			subscription = new SubscriptionImpl<N>(key, null, this);
			subscription.deactivate(Status.NORESOURCE);
		} else {
			assert root.getSubscription() == null;
			subscription = new SubscriptionImpl<N>(key, root, this);
		}

		SubscriptionImpl<N> s = dataLayer.registerSubscription(key, subscription,
				subscriber);

		if (subscription == s)
			subscriptions.put(key, subscription);

		return s;
	}

	public void unsubscribe(Key key) {
		SqlRootNode<N> root;

		try {
			root = getRoot(key);
			root.subscription = null;
		} catch (OperationFailedException e) {
			e.printStackTrace();
		}
	}

	public synchronized void deleteNode(Key key)
			throws OperationFailedException {
		try {
			rootMapping.delete(key);
		} catch (SQLException e) {
			throw new OperationFailedException(e);
		}
	}

	public Enumeration<Key> getKeys() {
		// TODO Implement getKeys
		// return null;
		throw new RuntimeException("Not implemented");
	}

	public Enumeration<Key> getKeys(KeyPattern pattern) {
		// TODO Implement getKeys
		// return null;
		throw new RuntimeException("Not implemented");
	}

	public final boolean isPersistent() {
		return true;
	}

	@Override
	public String toString() {
		return "SQL-PP(" + dataLayer.nodeType + ") " + names + " " + pattern
				+ " ";
	}
}
